﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;

namespace GoodStuff.Web
{
    /// <summary>
    /// Contains extensions for caching objects in the HttpContext.Items.
    /// </summary>
    public static class RequestCache
    {
        public static T CachedGet<T>(this IDictionary items, string key, Func<T> populate) where T : class
        {
            lock (items)
            {
                T value = items[key] as T;

                if (value == null)
                {
                    value = populate();
                    items[key] = value;
                }
                return value;
            }           
        }

        public static T CachedGet<T, TVary>(this IDictionary items, string key, TVary varyBy , Func<T> populate) where T : class where TVary : struct
        {
            lock (items)
            {
                string key2 = key + varyBy.ToString();
                T value = items[key2] as T;

                if (value == null)
                {
                    value = populate();
                    items[key2] = value;
                }
                return value;
            }
        }

        public static void CacheFlush(this IDictionary items, string key) 
        {
            lock (items)
            {
                items.Remove(key);
            }
        }

        public static void CacheFlush<TVary>(this IDictionary items, string key, TVary varyBy ) where TVary : struct
        {
            lock (items)
            {
                items.Remove(key + varyBy.ToString());
            }
        }
    }
}
